package com.filldream.fastboot.common.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.filldream.fastboot.common.entity.ErrorCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.InputStream;

@Service
public class AliOssUtil {

    @Value("${project.oss.endpoint}")
    private String endpoint;
    @Value("${project.oss.accessKeyID}")
    private String accessKeyId;
    @Value("${project.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${project.oss.bucket}")
    private String bucket;
    @Value("${project.oss.path}")
    private String path;




    /**
     * 上传文件
     * @param inputStream   文件inputStream
     * @param fileName  文件名称，例如：hello.jpg
     * @return
     */
    public String uploadInputStream(InputStream inputStream,String fileName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        fileName = path + "/" + fileName;
        ossClient.putObject(bucket, fileName, inputStream);
        ossClient.shutdown();
        return fileName;
    }

    public Boolean delByFilePath(String filePath) {
        Assert.isEmpty(filePath, ErrorCode.PARAM_ERR.diyMsg("filePath无效"));
        filePath = filePath.substring(filePath.lastIndexOf("/")).substring(1);
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        boolean exist = ossClient.doesObjectExist(bucket, filePath);
        Assert.checkBoolean( exist, ErrorCode.BASE_ERR.diyMsg( "文件不存在:" + filePath ));
        ossClient.deleteObject(bucket, filePath);
        ossClient.shutdown();
        return true;
    }
}
